package middleware.llvm.instruction;

import middleware.llvm.enums.CmpType;
import middleware.llvm.value.IRType;
import middleware.llvm.value.Value;

import java.io.PrintStream;

/**
 * 整数比较指令
 *
 * @author 杨凯伟
 * @date 2024/10/30
 */
public class ICmpInstruction extends Instruction {
    private final CmpType cond;


    private Value left;
    private Value right;

    public ICmpInstruction(CmpType cond, Value left, Value right) {
        super(IRType.getBool(), left, right);
        this.cond = cond;
        this.left = left;
        this.right = right;
//        assert left.getType().equals(right.getType());
    }

    public CmpType getCond() {
        return cond;
    }

    public void setLeft(Value left) {
        this.left = left;
    }

    public void setRight(Value right) {
        this.right = right;
    }

    public Value getLeft() {
        return left;
    }

    public Value getRight() {
        return right;
    }

    @Override
    public void replaceOperand(int pos, Value newOperand) {
        super.replaceOperand(pos, newOperand);
        switch (pos) {
            case 0 -> left = newOperand;
            case 1 -> right = newOperand;
        }
    }

    @Override
    public void dump(PrintStream out) {
        out.printf("  %s = icmp %s %s %s, %s\n",
                getName(),
                cond.name().toLowerCase(),
                left.getType().toString(),
                left.getName(),
                right.getName());
    }
}
